//
//  BBItemListView.swift
//  BusinessBao
//
//  Created by Chen on 2017/7/19.
//  Copyright © 2017年 Chen. All rights reserved.
//

import UIKit

public typealias itemSelectBlock = ((_ index: Int?) -> ())

class BBItemListView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {

    var selectBlock: itemSelectBlock?
    var collectionView: UICollectionView!
    let collectionViewFlowLayout = UICollectionViewFlowLayout()
    var dataArray = Array<Dictionary<String, String>>() {
        didSet {
            self.collectionView.reloadData()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        initView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initView() {
        let itemWidth = ScreenWidth / 4.0
        self.collectionViewFlowLayout.scrollDirection = .horizontal
        self.collectionViewFlowLayout.minimumLineSpacing = 0
        self.collectionViewFlowLayout.minimumInteritemSpacing = 10
        self.collectionViewFlowLayout.itemSize = CGSize(width: itemWidth, height: kRatio(number: 72))
        self.collectionViewFlowLayout.sectionInset = UIEdgeInsetsMake(kRatio(number: 15), 0, kRatio(number: 15), 0)
        self.collectionView = UICollectionView(frame: self.bounds,
                                          collectionViewLayout: self.collectionViewFlowLayout)
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.bounces = false
        self.collectionView.scrollsToTop = false
        self.collectionView.showsHorizontalScrollIndicator = false
        self.collectionView.backgroundColor = UIColor.white
        self.collectionView.register(BBItemCollectionCell.self,
                                forCellWithReuseIdentifier: NSStringFromClass(BBItemCollectionCell.self))
        self.addSubview(self.collectionView)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(BBItemCollectionCell.self), for: indexPath) as! BBItemCollectionCell
        cell.updateCell(data: self.dataArray[indexPath.item])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if (selectBlock != nil) {
            selectBlock!(indexPath.item)
        }
    }

}
